import dayjs from "dayjs";
import {hourToMinute, minuteToHour} from "@src/common/dateUtils";

Component({
  options: {
    addGlobalClass: true
  },
  properties: {},
  data: {
    visible: false,
    selectItem: ''
  },
  methods: {
    open(options) {
      return new Promise(((resolve, reject) => {
        let {shopInfo, appointMin, appointHour, isAppointTime} = options;
        let selectItem = "";
        if (isAppointTime) {
          selectItem = minuteToHour(appointMin + 60 * appointHour);
        }
        this.setData({selectItem: selectItem, visible: true, resolve: resolve, reject: reject});
        this.initTime(shopInfo);
      }))
    },
    handleSelect(e) {
      let item = e.currentTarget.dataset.item;
      this.setData({selectItem: item})
    },
    handleConfirm() {
      if (!this.data.selectItem) {
        this.data.resolve && this.data.resolve({isAppointTime: false, appointHour: 0, appointMin: 0})
      } else {
        let m = hourToMinute(this.data.selectItem)
        this.data.resolve && this.data.resolve({
          isAppointTime: true,
          appointTime: this.data.selectItem,
          appointHour: Math.floor(m / 60),
          appointMin: m % 60
        })
      }
      this.setData({visible: false, resolve: null, reject: null})
    },
    initTime(shopInfo) {
      // 可提前点餐时间, 单位分钟
      let delayTime = shopInfo.delayTime
      let closeTime = hourToMinute(shopInfo.closeTimeStr)
      let curTime = dayjs().hour() * 60 + dayjs().minute()
      let step = 15;
      // 取整数
      let startTime = curTime - (curTime % 15)
      if (curTime % 15 > 10) {
        startTime = startTime + 15;
      }
      let endTime = closeTime;
      if (startTime + delayTime < closeTime) {
        endTime = startTime + delayTime;
      }
      let timeList = ['']
      // 15分钟
      startTime += step
      while (startTime < endTime) {
        timeList.push(minuteToHour(startTime))
        startTime += step;
      }
      timeList.push(minuteToHour(endTime))
      this.setData({timeList: timeList, startTime: minuteToHour(curTime),  endTime: minuteToHour(endTime)})
    },
  }
});
